package com.dingreading.cloud.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.admin.entity.Corporations;
import com.dingreading.cloud.admin.entity.table.CorporationsTableDef;
import com.dingreading.cloud.admin.mapper.CorporationsMapper;
import com.dingreading.cloud.admin.service.CorporationsService;
import com.dingreading.cloud.common.util.PageDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class CorporationsServiceImpl extends BaseServiceImpl<CorporationsMapper, Corporations, CorporationsTableDef> implements CorporationsService {

    @Override
    protected CorporationsTableDef getTable() {
        return CorporationsTableDef.corporations;
    }

    @Override
    public PageDto<JSONObject> pageList(PageUtil pageUtil, String keyword, Integer contractStatus) {
        //设置其他参数
        Map<String, Object> otherParams = new HashMap<>();
        otherParams.put("keyword", keyword);
        otherParams.put("contractStatus", contractStatus);

        Page<JSONObject> page = getMapper().xmlPaginate("pageListXml", Page.of(pageUtil.getPage(), pageUtil.getRows()), otherParams);

        long totalRow = page.getTotalRow();
        List<JSONObject> list = page.getRecords();

        PageDto<JSONObject> dto = new PageDto<>();
        dto.setList(list);
        dto.setTotal(totalRow);

        return dto;
    }

    @Override
    public Corporations getByUid(String uid) {
        return getMapper().selectOneByCondition(table.uid.eq(uid));
    }

    @Override
    public List<Corporations> getByKeyword(String keyword) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (StringUtils.isNotBlank(keyword))
            condition.and(table.corpName.like(keyword));

        return getMapper().selectListByCondition(condition);
    }

    @Override
    public Corporations getLastUid(String yyMm) {
        QueryWrapper wrapper = QueryWrapper.create()
                .where(table.uid.likeLeft(yyMm))
                .orderBy(table.id.desc());

        return getMapper().selectOneByQuery(wrapper);
    }

    @Override
    public boolean existUid(String uid) {
        return exists(table.uid.eq(uid));
    }
}
